package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.DateSetmeal;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;


    //手机号快速登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) throws Exception {
        //从map中获取手机号及用户输入的验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中取出保存的验证码
        Jedis jedis = jedisPool.getResource();
        String validateCodeInRedis = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String nums = jedis.get(telephone + "login");
        //对验证码进行比对
        if (nums == null) {
            nums = "0";
        }
        Integer num = Integer.parseInt(nums);
        if (num >= 3) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR, num);
        }
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            //验证码校验成功,判断用户是否存在
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {//用户不存在,默认用户注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                //保存用户到会员表
                memberService.add(member);
            }
            //向客户端浏览器写入cookie,内容为手机号
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            //设置cookie跟随的路径"/"表示所有路径都跟随
            cookie.setPath("/");
            //设置cookie1存活时长
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //给cookie加密
            //获取cookie的value值
            String value = cookie.getValue();

            //获取base64编码器
            Base64.Encoder encoder = Base64.getEncoder();
            //编码
            telephone = encoder.encodeToString(value.getBytes());
            //把cookie的值转换成base编码形式
            cookie.setValue(telephone);
            //打印cookie的value值
            System.out.println(value + "????????????????//////////");
            //把加密后的cookie返回给客户端
            response.addCookie(cookie);


            //将会员信息保存到redis
            String json = JSON.toJSON(member).toString();
            jedis.setex(telephone, 60 * 30, json);
            jedis.close();
            return new Result(true, MessageConstant.LOGIN_SUCCESS, 0);
        } else {
            num = num + 1;
            jedis.setex(telephone + "login", 300, num.toString());
            jedis.close();
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR, num);
        }
    }

    //登录后根据cookie查找对应的会员信息
    @RequestMapping("/findMember")
    public Result getUsername(HttpServletRequest request) throws Exception {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("login_member_telephone".equals(cookie.getName())) {
               //base64编码后的cookie值
                String value= cookie.getValue();
                System.out.println(value+"/////////////////////////////////////////////////////??????????????????????????????????????????");
                //获取base64解码器
                Base64.Decoder decoder = Base64.getDecoder();
                //解码
                byte[] bytes= decoder.decode(value);
                System.out.println(bytes+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                String phoneNumber=new String(bytes);
                System.out.println(phoneNumber+"????????????????????????????????????????????????????????????????????????????????????????????????");
                Member member = memberService.findByTelephone(phoneNumber);
                return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS, member);
            }
        }
        return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
    }

    //查询会员信息
    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        try {
            memberService.edit(member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
    }


    //通过日期查询套餐信息
    @RequestMapping("/findByDate")
    public Result findByDate(HttpServletRequest request, @RequestBody Map map) {
        //回显用户信息
        String telephone = null; //创建一个变量,用于存储从cookie中的手机号;
        //1.登录后从cookie中获取手机号
        Cookie[] cookies = request.getCookies();
        telephone = null;
        //2.先判断cookie集合是否存在
        if (cookies != null) { //存在
            //2.1遍历cookie集合
            for (Cookie c : cookies) {
                //2.1.1判断此cookie是否为存手机号的键,并给telephone赋值
                if ("login_member_telephone".equals(c.getName())) {
                    //base64编码后的cookie值
                    String value= c.getValue();
                    //获取base64解码器
                    Base64.Decoder decoder = Base64.getDecoder();
                    //解码
                    byte[] bytes= decoder.decode(value);
                    String phoneNumber=new String(bytes);
                    telephone = phoneNumber;
                }
            }
        }
        System.out.println("测试是否可以获取前台发送的日期和cookie中的手机号:" + map.size() + ":::" + telephone);
        try {
            List<DateSetmeal> setmealList = memberService.findByDate(map, telephone);
            System.out.println("测试获取是否可以获取setmeal集合:" + setmealList.size());
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmealList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }


    //对应的查询套餐信息
    @RequestMapping("/findByOid")
    public Result findByOid(HttpServletRequest request, Integer oid) {
        //回显用户信息
        String telephone = null; //创建一个变量,用于存储从cookie中的手机号;
        //1.登录后从cookie中获取手机号
        Cookie[] cookies = request.getCookies();
        telephone = null;
        //2.先判断cookie集合是否存在
        if (cookies != null) { //存在
            //2.1遍历cookie集合
            for (Cookie c : cookies) {
                //2.1.1判断此cookie是否为存手机号的键,并给elephone赋值
                if ("login_member_telephone".equals(c.getName())) {
                    //base64编码后的cookie值
                    String value= c.getValue();
                    //获取base64解码器
                    Base64.Decoder decoder = Base64.getDecoder();
                    //解码
                    byte[] bytes= decoder.decode(value);
                    String phoneNumber=new String(bytes);
                    telephone = phoneNumber;
                }
            }
        }
        System.out.println("测试是否可以获取oid和cookie中的手机号:?/?/?/?/?///?/?/?///?//?////?///?" + oid + ":::" + telephone);
        try {
            List<DateSetmeal> setmealList = memberService.findByOid(telephone, oid);
            System.out.println("测试获取是否可以获取setmeal集合:" + setmealList.size());
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS, setmealList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
        }
    }


}

